/*
 * @Author: xiaosihan
 * @Date: 2022-08-20 14:50:15
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-05-06 02:16:22
 */
import editorStore from '@/editorComponent/editorStore';
import preview3DRenderer from '@/editorComponent/preview3DRenderer';
import { autorun } from 'mobx';
import { Quaternion, SRGBColorSpace, Vector3 } from 'three';
import ThreeBase from 'three-base';

// 预览弹窗内的3d渲染器
class PreviewModal3DRenderer extends ThreeBase {
  constructor() {
    super();
    this.setCameraType('orthographicCamera');
  }

  //纹理有更新时需要渲染
  dispose = autorun(() => {
    this.needRender = editorStore.needUpdateTime > 0;
  });

  init() {
    super.init();
    this.gridHelper.visible = false;
    this.axesHelper.visible = false;
    this.renderer.outputColorSpace = SRGBColorSpace;
    this.scene = preview3DRenderer.scene;
    this.orthographicCamera.far = 5010;
    this.orthographicCamera.near = 4990;
    this.orthographicCamera.updateProjectionMatrix();
    // this.controls.rotateSpeed = 2;
    // this.autoRender = false;
    // this.resetLookAt({
    //     center: new Vector3(0, 0, 0),
    //     position: new Vector3(0, 0, 7)
    // });
  }

  async setContainer(div: HTMLDivElement | null) {
    await new Promise((resolve) => requestAnimationFrame(resolve));
    await super.setContainer(div);
    await new Promise((resolve) => requestAnimationFrame(resolve));
    const { left, right, top, bottom, position } = preview3DRenderer.orthographicCamera;
    Object.assign(this.orthographicCamera, { left, right, top, bottom });
    this.orthographicCamera.position.copy(position);
    // this.orthographicCamera.lookAt(this.scene.position);
    // this.controls.target.copy(preview3DRenderer.controls.target);
    this.orthographicCamera.updateProjectionMatrix();

    // this.perspectiveCamera.position.copy(preview3DRenderer.perspectiveCamera.position);
    // this.perspectiveCamera.lookAt(preview3DRenderer.controls.target);
    // this.controls.target.copy(preview3DRenderer.controls.target);
    // this.renderer.clear();
    // this.renderer.render(preview3DRenderer.scene, this.perspectiveCamera);
    this.needRender = true;
  }

  render(): void {
    // preview3DRenderer.pointLight1.position.copy(this.orthographicCamera.position);
    super.render();
    // if (this.controls.enabled) {
    //     this.controls.update();
    // }
    // this.renderer.clear();
    // this.renderer.render(preview3DRenderer.scene, this.perspectiveCamera);
  }
}

const previewModal3DRenderer = (window.previewModal3DRenderer = new PreviewModal3DRenderer());

export default previewModal3DRenderer;
